
package com.gps.gate;

import com.gps.gate.protocol.Jt808Protocol;
import com.gps.gate.protocol.HttpProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ServerManager {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServerManager.class);
    private final List<TrackerServer> serverList = new LinkedList<>();
    private final Map<String, BaseProtocol> protocolList = new ConcurrentHashMap<>();

    private Class<?>[] protCls = new Class[] {
            HttpProtocol.class,
            Jt808Protocol.class
    };

//    public ServerManager() throws Exception {
//    }

    @PostConstruct
    private void init() throws Exception {
        for (Class<?> cls : protCls) {
            BaseProtocol protocol = (BaseProtocol) cls.newInstance();
            serverList.addAll(protocol.getServerList());
            protocolList.put(protocol.getName(), protocol);
        }
    }

    public BaseProtocol getProtocol(String name) {
        return protocolList.get(name);
    }

    public void start() {
        LOGGER.info("=============================begin start server===================");
        for (TrackerServer server: serverList) {
            try {
                server.start();
                LOGGER.info("start port end: " + server.getPort());
            } catch (Exception e) {
                LOGGER.warn("Port {} is disabled due to conflict", server.getPort());
            }
        }
        LOGGER.info("=============================end start server===================");
    }

    public void stop() {
        for (TrackerServer server: serverList) {
            LOGGER.info("server stop: " + server.getPort());
            server.stop();
        }
        GlobalTimer.release();
    }

}
